let companyMethod = require("../dao/companyListDAO").companyMethod;

// 新增企业
exports.addCompany = function (req, res){
  companyMethod.findOne({companyName:req.body.companyName}, function (err, doc){
    if(!err){
      if(!doc){
        let newCompany = {companyName: req.body.companyName, companyDes: req.body.companyDes};
        companyMethod.save(newCompany, function (err){
          if(!err){
            res.send({
              code: 200,
              msg: "新增成功！"
            });
          }
        });
      }else{
        res.send({
          code: 201,
          msg: "企业名已被占用！"
        });
      }
    }
  });
};


// 获取企业列表
exports.getCompanyList = function (req, res){
  companyMethod.findAll(function (err, doc) {
    if(!err){
      res.send({
        code: 200,
        data: doc,
        msg: "查询成功！"});
    }
    else{
      res.send({
        code: 201,
        msg: "查询失败！"});
    }
  })
};

// 删除
exports.delCompany = function (req, res){
  let id = req.body.id
  // 根据id查询单条数据
  companyMethod.findOne({_id: req.body.id},function (err, doc) {
    if(!err && doc){
      let par = {
        _id: id
      }
      // 删除单条数据
      companyMethod.remove(par,function (err, doc) {
        if(!err){
          res.send({
            code: 200,
            msg: "删除成功！"});
        }else{
          res.send({
            code: 200,
            msg: "删除失败！"});
        }
      })
    }
  })
};

// 修改
exports.editCompany = function (req, res) {
  let newCompany = {companyName: req.body.companyName, companyDes: req.body.companyDes};
  console.log(newCompany,req.body.id)
  // 查询单个数据
  companyMethod.findOne({_id: req.body.id},function (err, doc) {
    if(!err && doc){
      // 更新单个数据
      companyMethod.update({_id:req.body.id},newCompany,function (err) {
        if(!err){
          res.send({
            code: 200,
            msg: "修改成功！"});
        }
        else{
          res.send({
            code: 201,
            msg: "修改失败！"});
        }
      })
    }
  })
}
